<?php
namespace app\oa\controller;

use app\oa\ext\Role;
use app\oa\ext\UserStatus;
use app\oa\model\Task;
use app\oa\model\User;
use think\Controller;
use think\Request;

class Index extends Controller {
    protected function _initialize()
    {
        parent::_initialize();
        if(!UserStatus::isLogin()) {
            if($this->request->action() != "login") {
                $this->redirect("login");
            }
        }
    }

    public function login(Request $request) {
        if($request->isGet()) {
            return $this->fetch();
        }else {
            // 验证码
            if(!captcha_check($request->param("captcha"))) {
                $this->error("验证码错误");
            }

            // 验证用户
            $map['username'] = $request->param("username");
            $map['password'] = md5(config('salt') . $request->param("password"));
            $user = User::get($map);
            if($user) {
                UserStatus::login($user['id'], $user['username'], $user['role'], $user['department_id']);
                $this->success("登录成功", "index");
            }else {
                $this->error("用户名或密码错误");
            }
        }

    }


    public function index(Request $request) {
        $info = UserStatus::getUserInfo();
        $c = null;
        switch ($info['role']) {
            case Role::Employee:
                $c = new Employee($request);
                break;
            case Role::DeputySupervisor:
            case Role::Supervisor:
                $c = new Supervisor($request);
                break;
            case Role::DeputyDirector:
            case Role::Director:
                $c = new Director($request);
                break;
            case Role::DeputySecretary:
            case Role::Secretary:
                $c = new Secretary($request);
                break;
            case Role::Boss:
                $c = new Boss($request);
                break;
        }
        if($c != null) {
            return $c->index();
        }else {
            $this->error("错误");
        }
    }

    public function logout() {
        UserStatus::logout();
        $this->redirect("login");
    }




}